<?php
	include_once "../include/Functions.php";
	//include_once "include/Functions.php";
	
	$exercise_id= $_GET['exercise_id'];
	$person_id = $_GET['user_id'];
	
	//echo "exercise_id = ".$exercise_id;
	//Calcula as conquistas pessoais
	function searchAchievement($statistics, $km){
		if( count($statistics) <= $km )
			return;
		
		$last = count($statistics) - 1;
		$index = floor($statistics[$last]['km']);
		
		//echo "Index: {$index}\n";
		$sum =0;
		for($i=0; $i < $km; $i++)
			$sum += $statistics[$i]['d_time'];
			
		$min = $sum;
		for($i=$km; $i < $index; $i++){
			$sum= $sum - $statistics[$i-$km]['d_time'] + $statistics[$i]['d_time'];
			//echo "Sum {$i}: {$sum}\n";
			if( $sum < $min)
				$min= $sum;
		}
		return $min;
	}
	
	function updateAchievement($statistics, $distance, $date, $person_id, $exercise_id, $type_id){
		$min = searchAchievement($statistics, $distance);
      //echo $min;
		$sql = "INSERT INTO achievement (person_id, km , d_time, date_time, exercise_id, type_id) VALUES
				({$person_id},
				{$distance},
				{$min},
				{$date},
				{$exercise_id},
				{$type_id});";
				
		Functions::execSql($sql);
		
		//ADD distinct exercise_id
		$sql = "DELETE 
				FROM achievement 
				WHERE 
					person_id= {$person_id} AND
					km = {$distance} AND 
					type_id = {$type_id} AND 
					id 	NOT IN (SELECT * 
								FROM (  SELECT id 
										FROM achievement 
										WHERE 
											person_id= {$person_id} AND
											km = {$distance} AND 
											type_id = {$type_id}
										ORDER BY d_time
										LIMIT 10)
									AS t)";
                           
      //echo $sql;
		Functions::execSql($sql);
	}
	
	$sql = "SELECT * 
			FROM estatistics 
			WHERE id_exerc = {$exercise_id}
				AND id_person = {$person_id}
			ORDER BY km;";
	
	$statistics = Functions::getDataSql($sql);
		
	$sql = "SELECT  duration, distance, ex_date_time, id_type
				FROM `exercise` 
				WHERE id = {$exercise_id}
				AND id_person = {$person_id};";		
	
	//echo $sql;
	$ex = Functions::getArraySql($sql);
	
	$type_id = $ex['id_type'];
	$distance = floor($ex['distance']);
	if( $distance >= 1){
		updateAchievement($statistics, 1, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}
	if( $distance >= 5 ){
		updateAchievement($statistics, 5, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}
	if( $distance >= 10){
		updateAchievement($statistics, 10, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}
	if( $distance >= 21){
		updateAchievement($statistics, 21, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}
	if( $distance >= 42){
		updateAchievement($statistics, 42, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}
	if( $distance >= 100){
		updateAchievement($statistics, 100, $ex["ex_date_time"], $person_id, $exercise_id, $type_id);
	}	
?>